var common = {};

common.validate = function (data, rules) {
    /**
     * rules are rule array, values in [require,email,tel,maxLen:Number,minLen:Number,reg:RegExp]
     * */
    var result = [];
    var validator = {
        require: function () {
            if (!!data && data.trim().length != 0) {
                return true;
            } else {
                return "未填写必填项";
            }
        },
        email: function () {
            if (data.match(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/)) {
                return true;
            } else {
                return "电子邮箱有误";
            }
        },
        tel: function () {
            if (data.length == 11 && data.match(/\d/)) {
                return true;
            } else {
                return "手机号码有误";
            }
        },
        maxLen: function (max) {
            if (data.trim().length <= max) {
                return true;
            } else {
                return "超过最大长度";
            }
        },
        minLen: function (min) {
            if (data.trim().length >= min) {
                return true;
            } else {
                return "输入长度过短";
            }
        },
        reg: function (regStr) {
            if (data.match(new RegExp(regStr))) {
                return true;
            } else {
                return "输入不合要求";
            }
        }
    };

    if (rules instanceof Array) {
        rules.forEach(function (e) {
            collectResult(e);
        });
    } else {
        collectResult(rules);
    }

    function collectResult(rule) {
        var tempRes = "";
        if (rule.indexOf(':') == -1) {
            tempRes = validator[rule]();
        } else {
            tempRes = validator[rule.substring(0, rule.indexOf(':'))](rule.substring(rule.indexOf(':') + 1, rule.length));
        }
        if (tempRes != true) {
            result.push(tempRes);
        }
    }

    if (result.length == 0) return true;
    else return result;

};

common.toast = function (type, msg) {
    //todo switch type[warning,error,success] and display different label
    var color = {
        success: 'rgb(223,240,216)',
        warning: 'rgb(252,248,227)',
        error: 'rgb(242,222,222)',
        info: 'rgb(217,237,247)'
    };
    if (!!msg) {
        if ($("#modalInstance").length != 0) {
            $("#modalInstance").css('background-color', color[type]);
            $("#modalContent").html(msg);
            $("#modalInstance").fadeIn(700, function () {
                setTimeout(function () {
                    $("#modalInstance").fadeOut(600);
                }, 2500);
            });
        } else {
            var html = '<div id="modalInstance" style="position: fixed;top:45px;left:11%;' +
                'width: 78%;height: 25px;z-index: 999;border-radius: 10px;display: none">' +
                '<div id="modalContent" style="margin:3px 5px 3px 5px;width: 100%;text-align: center;' +
                'color: #888;font-size: 16px;opacity: 1;"></div></div>';
            $("body").append(html);
            common.toast(type, msg);
        }
    }
};

common.modal = function () {
    var html = '<div class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header">' +
        '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
        '<h4 class="modal-title">' + arguments[0] + '</h4>' +
        '</div><div class="modal-body">';

    for (var i = 1; i < arguments.length; i++) {
        //todo
    }
    html += '</div><div class="modal-footer">\
    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>\
    <button type="button" class="btn btn-primary">确定</button></div></div></div></div>';
};

common.bdMap = function (config) {
    window.unique_marker = null; //unique marker
    var defaultConfig = {
        container: "bdMapContainer", //map container id
        inputContainer: "bdMapInput", //auto complete container
        element: ["bdMap", "geoInput", "completePanel"], //map element ids
        nav: true,  //navigation
        geo: true, //geoLocation
        auto: true, //autoComplete
        init: {lng: 121.629, lat: 31.086}, //initial position
        level: 16
    };

    /**
     *  1. handle config
     * */
    for (var i in config) {
        if (!!defaultConfig[i]) {
            defaultConfig[i] = config[i];
        }
    }

    if (!defaultConfig.auto) {
        $("#" + defaultConfig.element[0]).css("height", "100%");
        $("#" + defaultConfig.element[0]).css("top", "0");
        $("#" + defaultConfig.element[0]).attr('style', "height: 100%;width: 100%;");
    } else {
        $("#" + defaultConfig.element[0]).attr('style', "height: 92%;width: 100%;position: absolute;top:8%");
        $("#" + defaultConfig.inputContainer).show();
    }
    $("#" + defaultConfig.container).show();

    /**
     *  2. init map
     * */
    var map = new BMap.Map(defaultConfig.element[0]);
    map.enableScrollWheelZoom();
    map.enableInertialDragging();
    map.enableContinuousZoom();
    map.centerAndZoom(new BMap.Point(defaultConfig.init.lng, defaultConfig.init.lat), defaultConfig.level);
    addMapListener();

    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            window.unique_marker = new BMap.Marker(r.point);
            map.addOverlay(window.unique_marker);
            map.panTo(r.point);
            addMarkerListener();
        }
        else {
            alert('failed' + this.getStatus());
        }
    }, {enableHighAccuracy: true});

    /**
     *  3. add optional components
     * */
    if (defaultConfig.nav) {
        var navigationControl = new BMap.NavigationControl({
            anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
            type: BMAP_NAVIGATION_CONTROL_LARGE,
            enableGeolocation: true
        });
        map.addControl(navigationControl);
    }

    if (defaultConfig.geo) {
        var geolocationControl = new BMap.GeolocationControl();
        geolocationControl.addEventListener("locationSuccess", function (e) {
            map.clearOverlays();
            map.centerAndZoom(e.point, defaultConfig.level);
            window.unique_marker = new BMap.Marker(e.point);
            map.addOverlay(window.unique_marker);
            addMarkerListener();
        });

        geolocationControl.addEventListener("locationError", function (e) {
            window.utils.toast('error', e.message);
        });
        map.addControl(geolocationControl);
    }

    /**
     *  4. auto complete component
     * */
    if (defaultConfig.auto) {
        var ac = new BMap.Autocomplete({"input": defaultConfig.element[1], "location": map});

        function G(id) {
            return document.getElementById(id);
        }

        ac.addEventListener("onhighlight", function (e) {
            var str = "";
            var _value = e.fromitem.value;
            var value = "";
            if (e.fromitem.index > -1) {
                value = _value.province + _value.city + _value.district + _value.street + _value.business;
            }
            str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

            value = "";
            if (e.toitem.index > -1) {
                _value = e.toitem.value;
                value = _value.province + _value.city + _value.district + _value.street + _value.business;
            }
            str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
            G(defaultConfig.element[2]).innerHTML = str;
        });

        var myValue;
        ac.addEventListener("onconfirm", function (e) {
            var _value = e.item.value;
            myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
            G(defaultConfig.element[2]).innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
            $("#" + defaultConfig.element[2]).hide();
            setPlace();
        });
        function setPlace() {
            map.clearOverlays();
            window.unique_marker = null;
            function searchFunction() {
                var pp = local.getResults().getPoi(0).point;
                map.centerAndZoom(pp, defaultConfig.level);

                window.unique_marker = new BMap.Marker(pp);
                map.addOverlay(window.unique_marker);
                addMarkerListener();
            }

            var local = new BMap.LocalSearch(map, {
                onSearchComplete: searchFunction
            });
            local.search(myValue);
        }
    }

    /**
     *  5. add click listener
     * */
    function addMarkerListener() {
        var geoc = new BMap.Geocoder();
        geoc.getLocation(window.unique_marker.point, function (rs) {
            var addComp = rs.addressComponents;
            var msg = addComp.city + "" + addComp.district +
                "" + addComp.street + "" + addComp.streetNumber;
            if (!!rs.surroundingPois[0]) {
                msg += rs.surroundingPois[0].title;
            }
            window.unique_marker.m_addr_info = msg;
            var opts = {
                width: 130,
                height: 80,
                title: "<h5>选取位置</h5>"
            };
            var infoWindow = new BMap.InfoWindow(msg, opts);
            map.openInfoWindow(infoWindow, window.unique_marker.point);
        });
    }

    function addMapListener() {
        map.addEventListener("click", function (e) {
            map.clearOverlays();
            window.unique_marker = new BMap.Marker(e.point);
            map.addOverlay(window.unique_marker);
            addMarkerListener();
        });
    }

    map.m_config = defaultConfig;
    map.closeMap = function () {
        defaultConfig.auto && $("#" + defaultConfig.inputContainer).hide();
        $("#" + defaultConfig.container).hide();
    };
    return map;
};

common.mapSearch = function (p1, p2,map,callback) {
    var point1 = new BMap.Point(p1.split(",")[0],p1.split(",")[1]);
    var point2 = new BMap.Point(p2.split(",")[0],p2.split(",")[1]);
    var result = {},transit = null;
    var routeOption = {
        onSearchComplete: function(results){
            if (transit.getStatus() != BMAP_STATUS_SUCCESS){
                return ;
            }
            var plan = results.getPlan(0);
            result.distance = plan.getDistance(false) / 1000;
            result.duration = plan.getDuration(true);
            callback(result);
        }
    };
    transit = new BMap.DrivingRoute(map, routeOption);
    transit.search(point1, point2);
};

common.Timer = function (circleid) {
    var count = 0;
    var timer;
    this.start = function () {
        var circleELe = document.getElementById(circleid);
        var countHeader = '<p  style="margin-top: 35%;margin-left: 35%;color: white;font-size: 200px">'
        var countFooter = 's</p>'

        countContent.innerHTML = countHeader + count + countFooter;
        count = count + 1;
        timer = setTimeout("start()", 1000);
    };

    this.stop = function () {
        clearTimeout(timer);
    }
}

window.utils = common;